#!/bin/sh
# Copyright (C) 2020 Tano Systems LLC

#
# Some target devices (e.g., mangOH) do not have a dedicated MAC address set.
# Every time you reboot the device it will grab a new IP address and may
# be confusing to connect to.
#
# To resolve this problem when the system boots up, we save the MAC address
# of the interface to the overlay file system and restore it every time
# it boots up.
#

IFNAME="eth0"
SAVED_FILE="/etc/${IFNAME}_address"
CURRENT_FILE="/sys/class/net/${IFNAME}/address"

do_setup_iface_mac() {
	case $(board_name) in
		qcom,mdm9607-mtp)
			[ -f "${CURRENT_FILE}" ] || return

			CURRENT_MAC=`cat ${CURRENT_FILE}`
			echo "eth0: current (autogenerated) MAC '${CURRENT_MAC}'" > /dev/kmsg

			if [ -s "${SAVED_FILE}" ]; then
				# Restore saved MAC
				SAVED_MAC=`cat ${SAVED_FILE}`
				ip link set dev ${IFNAME} down 2>/dev/null
				ip link set ${IFNAME} address ${SAVED_MAC} 2>/dev/null
				ip link set dev ${IFNAME} up 2>/dev/null
				echo "eth0: restored MAC '${SAVED_MAC}' from '${SAVED_FILE}'" > /dev/kmsg
			else
				# Save current MAC
				echo ${CURRENT_MAC} > ${SAVED_FILE}
				echo "eth0: saved MAC '${CURRENT_MAC}' to '${SAVED_FILE}'" > /dev/kmsg
			fi
			;;
	esac
}

boot_hook_add preinit_mount_root do_setup_iface_mac
